#!/usr/bin/env python3
#
# This is a simple script to download Windows installers from AppVeyor.
# Use this script to automate the Windows release process.
#
# USAGE
#
#   $ appveyor-download v1.2.1  # Download installers for v1.2.1
#

import json
import sys
import os
import urllib.request
import datetime

#
# GLOBAL VARIABLES

GITHUB_URL = 'https://api.github.com/repos/fluent/fluent-bit/statuses/%s'

APPVAYOR_JOBS = 'https://ci.appveyor.com/api/projects/fluent/%s/builds/%s'
APPVAYOR_LIST = 'https://ci.appveyor.com/api/buildjobs/%s/artifacts'
APPVAYOR_FILE = 'https://ci.appveyor.com/api/buildjobs/%s/artifacts/%s'

#
# Util functions

def now():
    return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

def usage():
    print('Usage: appveyor-download VERSION')
    return -1

def LOG(*args):
    print(now(), *args, file=sys.stderr)

#
# REST API

def json_api(url):
    LOG('Request %s' % url)
    with urllib.request.urlopen(url) as fp:
        return json.loads(fp.read().decode())

def build_get(version):
    resp = json_api(GITHUB_URL % version)

    for item in resp:
        if item['description'] == 'AppVeyor build succeeded':
            build_url = item['target_url']
            break
    else:
        raise RuntimeError('No AppVeyor build found: %s' % resp)

    tokens = build_url.split('/')

    return (tokens[-3], tokens[-1])

def jobs_get(project_id, build_id):
    resp = json_api(APPVAYOR_JOBS % (project_id, build_id))
    return list(node['jobId'] for node in resp['build']['jobs'])

def filenames_get(job_id):
    resp = json_api(APPVAYOR_LIST % job_id)
    return list(node['fileName'] for node in resp)

#
# Main

def main(args):
    if not args:
        return usage()

    project_id, build_id = build_get(args[0])

    for job_id in jobs_get(project_id, build_id):
        for filename in filenames_get(job_id):

            with urllib.request.urlopen(APPVAYOR_FILE % (job_id, filename)) as fp:
                data = fp.read()
                size = len(data)

            outfile = os.path.basename(filename)
            with open(outfile, 'wb') as fw:
                fw.write(data)

            LOG('* %s (%s bytes)' % (outfile, size))

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))
